import 'package:get/get.dart';
import 'package:nyh_motorcade_app/constant/constant.dart';
import 'package:nyh_motorcade_app/entity/company_entity.dart';
import 'package:nyh_motorcade_app/entity/transaction_flow_entity.dart';
import 'package:nyh_motorcade_app/http/http_address.dart';
import 'package:nyh_motorcade_app/http/http_manager.dart';
import 'package:nyh_motorcade_app/routes/routes.dart';
import 'package:nyh_motorcade_app/utils/date_utils.dart';
import 'package:nyh_motorcade_app/utils/sp_utils.dart';
import 'package:nyh_motorcade_app/utils/toast_utils.dart';
import 'package:nyh_motorcade_app/widgets/multi_state/multi_state_widget.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';

class TransactionFlowController extends GetxController {
  RefreshController refreshController = RefreshController();
  MultiState multiState = MultiState.loading;
  String companyId = "";
  String companyName = "";
  List<CompanyEntity> companyList = [];
  String startDate = "";
  String endDate = "";
  int page = 1;
  List<DateType> dateTypeList = [];
  bool showDateTypeMenu = false;
  String selectDateName = "";
  double orderAmount = 0.0;
  int orderCount = 0;
  List<TransactionFlowPageVoItem> transactionFlowList = [];

  //查询类型:全部、司机和车辆
  String queryType = "";

  //司机ID
  String driverId = "";

  //车辆ID
  String vehicleId = "";

  @override
  void onInit() {
    super.onInit();
    initDateTypeList();
  }

  @override
  void onReady() {
    super.onReady();
    dynamic arguments = Get.arguments;
    if (arguments != null && arguments is Map) {
      queryType = arguments[Constant.PARAM_TYPE] ?? "";
      if (queryType.isNotEmpty) {
        if (queryType == Constant.DRIVER) {
          driverId = arguments[Constant.PARAM_SOURCE_ID] ?? "";
        } else {
          vehicleId = arguments[Constant.PARAM_SOURCE_ID] ?? "";
        }
      } else {
        companyId = arguments[Constant.PARAM_COMPANY_ID] ?? "";
        companyName = arguments[Constant.PARAM_COMPANY_NAME] ?? "";
        companyList = arguments[Constant.PARAM_COMPANY_LIST] ?? [];
      }
      startDate = dateTypeList[0].startDate!;
      endDate = dateTypeList[0].endDate!;
      selectDateName = dateTypeList[0].name;
      update();
      getTransactionFlow();
    }
  }

  Future<void> onRefresh() async {
    page = 1;
    getTransactionFlow();
  }

  Future<void> onLoading() async {
    getTransactionFlow();
  }

  void onRetry() {
    transactionFlowList.clear();
    multiState = MultiState.loading;
    update();
    getTransactionFlow();
  }

  void goToSearchTransactionFlowPage() async {
    if (companyId.isEmpty) {
      companyId = await SPUtils.getString(SPUtils.COMPANY_ID);
    }
    Get.toNamed(Routes.searchTransactionFlow, arguments: companyId);
  }

  Future<void> getTransactionFlow() async {
    httpManager.post(
      Get.context,
      HttpAddress.GET_TRANSACTION_FLOW,
      {
        "superId": companyId.isNotEmpty ? companyId : await SPUtils.getString(SPUtils.COMPANY_ID),
        "driverId": driverId,
        "vehicleId": vehicleId,
        "startDate": startDate.isNotEmpty ? startDate + " 00:00:00" : null,
        "endDate": endDate.isNotEmpty ? endDate + " 23:59:59" : null,
      },
      headers: {"page": page, "limit": 10},
      isToast: true,
      onSuccess: (data) {
        if (data == null) {
          ToastUtils.toast("请求失败");
          if (refreshController.isRefresh) {
            refreshController.refreshFailed();
          } else {
            refreshController.loadFailed();
          }
          if (page == 1) {
            multiState = MultiState.fail;
          }
          update();
          return;
        }
        TransactionFlowEntity transactionFlowEntity = TransactionFlowEntity().fromJson(data);
        orderAmount = transactionFlowEntity.orderAmount ?? 0.0;
        orderCount = transactionFlowEntity.pageVo!.total ?? 0;
        List<TransactionFlowPageVoItem> list = transactionFlowEntity.pageVo!.item ?? [];
        if (list.isNotEmpty) {
          multiState = MultiState.success;
          if (refreshController.isRefresh) {
            transactionFlowList.clear();
            refreshController.refreshCompleted();
          } else {
            if (list.length >= 10 || page == 1) {
              refreshController.loadComplete();
            } else {
              refreshController.loadNoData();
            }
          }
          if (page == 1) {
            transactionFlowList.clear();
          }
          transactionFlowList.addAll(list);
          page++;
        } else {
          if (refreshController.isRefresh) {
            refreshController.refreshCompleted();
          } else {
            refreshController.loadNoData();
          }
          if (page == 1) {
            multiState = MultiState.empty;
          }
        }
        update();
      },
      onFail: (code, msg) {
        if (refreshController.isRefresh) {
          refreshController.refreshFailed();
        } else {
          refreshController.loadFailed();
        }
        if (page == 1) {
          multiState = MultiState.fail;
        }
        update();
      },
      onError: (msg) {
        if (refreshController.isRefresh) {
          refreshController.refreshFailed();
        } else {
          refreshController.loadFailed();
        }
        if (page == 1) {
          multiState = MultiState.error;
        }
        update();
      },
    );
  }

  Future<void> changeCompany() async {
    if (companyList.length <= 1) {
      return;
    }
    dynamic data = await Get.toNamed(Routes.changeCompany);
    if (data != null && data is Map) {
      String id = data[Constant.PARAM_COMPANY_ID];
      if (companyId != id) {
        companyId = id;
        companyName = data[Constant.PARAM_COMPANY_NAME];
        transactionFlowList.clear();
        page = 1;
        multiState = MultiState.loading;
        update();
        getTransactionFlow();
      }
    }
  }

  void initDateTypeList() {
    dateTypeList.add(
      DateType(
        name: "近一周",
        startDate: DateUtil.subtractDate(Duration(days: 6)),
        endDate: DateUtil.getCurrentDate(),
      ),
    );
    dateTypeList.add(
      DateType(
        name: "近一月",
        startDate: DateUtil.subtractDate(Duration(days: 30)),
        endDate: DateUtil.getCurrentDate(),
      ),
    );
    dateTypeList.add(
      DateType(
        name: "近三月",
        startDate: DateUtil.subtractDate(Duration(days: 90)),
        endDate: DateUtil.getCurrentDate(),
      ),
    );
    dateTypeList.add(
      DateType(
        name: "自定义",
        startDate: "",
        endDate: "",
      ),
    );
  }

  void setSelectDateType(int? value) {
    showDateTypeMenu = false;
    if (value != null) {
      if (value == dateTypeList.length - 1) {
        goToSelectDatePage();
        return;
      }
      String start = dateTypeList[value].startDate ?? "";
      String end = dateTypeList[value].endDate ?? "";
      String name = dateTypeList[value].name;
      if (startDate != start) {
        startDate = start;
        endDate = end;
        selectDateName = name;
        transactionFlowList.clear();
        page = 1;
        multiState = MultiState.loading;
        getTransactionFlow();
      }
    }
    update();
  }

  Future<void> goToSelectDatePage() async {
    dynamic data = await Get.toNamed(Routes.selectDate);
    showDateTypeMenu = false;
    if (data != null && data is Map) {
      startDate = data[Constant.PARAM_START_DATE];
      endDate = data[Constant.PARAM_END_DATE];
      selectDateName = startDate + "至" + endDate;
      transactionFlowList.clear();
      page = 1;
      multiState = MultiState.loading;
      getTransactionFlow();
    }
    update();
  }
}

class DateType {
  String? startDate;
  String? endDate;
  String name;

  DateType({required this.name, required this.startDate, required this.endDate});
}
